var result = {success: false};
var preferences = null;
var widgetUrl = 'https://moscowsg.megafon.ru/WIDGET_INFO/GET_INFO?X_Username=%LOGIN%&X_Password=%PASSWORD%&CHANNEL=WYANDEX&LANG_ID=1&P_RATE_PLAN_POS=1&P_PAYMENT_POS=2&P_ADD_SERV_POS=4&P_DISCOUNT_POS=3';
var dataElement = null;

var bonuses =
{
	'megafon_moscow': 'на МегаФон Московского рег-на',
	'megafon_net': 'на Единую сеть МегаФон',
	'competitors': 'на МТС, Билайн, Скай Линк'
};

Ajax =
{
	callback: [],
	get: function()
	{
		Ajax.callback['ERROR'] = function(json)
		{
			return json;
		}
		Ajax.callback['WYANDEX'] = function(json)
		{
			return json;
		}
		var html = AnyBalance.requestGet(widgetUrl);
		return eval(html);
	}
};

function GetData()
{
	try
	{
		var json = Ajax.get();
		if(!json)
		{
			throw new AnyBalance.Error('Неверный ответ сервера.');
		}
		if(!json.ok)
		{
			throw new AnyBalance.Error(json.error.text2);
		}
		return json.ok.html;
	}
	catch(e)
	{
		if(e.skip)
		{
			throw e;
		}
		throw new AnyBalance.Error('Не удалось получить данные: ' + e.message);
	}
}

function SumDiscount(element)
{
	var result = 0;
	element.each(function()
	{
		result += parseFloat(this.textContent);
	});
	return result * 60;
}

function MinDate(element)
{
	var result = null;
	element.each(function()
	{
		var date = moment(this.textContent, "DD.MM.YYYY");
		if(result == null || date < result)
		{
			result = date;
		}
	});
	return result;
}

function ParseData(html)
{
	$(html).not('script').appendTo(dataElement);
}

function SetCounters()
{
	if(AnyBalance.isAvailable('BALANCE'))
	{
		var matches = /^([\d.]+)\s+(\D+)$/.exec($('.header .balance .subs_balance').text());
		if(!matches)
		{
			throw new AnyBalance.Error('Не удалось получить баланс');
		}
		result['BALANCE'] = parseFloat(matches[1]);
		result['CURRENCY'] = matches[2];
	}
	
	if(AnyBalance.isAvailable('BONUS_BALANCE'))
	{
		result['BONUS_BALANCE'] = parseFloat($('.header .balance .bonus').text());
	}
	
	if(AnyBalance.isAvailable('COSTS'))
	{
		var matches = /^\D+\s+([\d.]+)\s+\D+$/.exec($('.header .costs').text());
		if(!matches)
		{
			throw new AnyBalance.Error('Не удалось получить расходы');
		}
		result['COSTS'] = matches[1];
	}

	for(var counterName in bonuses)
	{
		var counterNameBalance = (counterName + '_balance').toUpperCase();
		var counterNameDate = (counterName + '_date').toUpperCase();

		var discount = $('.discount_table .cc_discount_row').has('div:contains("' + bonuses[counterName] +'")').filter(function(){
			return parseFloat($(this).children('.discount_volume').children('[title="Остаток абонента"]').text()) > 0;
		}).children('.discount_volume');
		if(AnyBalance.isAvailable(counterNameBalance))
		{
			result[counterNameBalance] = SumDiscount(discount.children('[title="Остаток абонента"]'));
			if(AnyBalance.isAvailable(counterNameDate))
			{
				var dates = discount.parent().siblings().children('.date').filter(function(){
					return this.innerText.match(/^по /);
				});
				if(AnyBalance.isAvailable(counterNameDate))
				{
					result[counterNameDate] = MinDate(dates).format(preferences.date_format);
				}
			}
		}
	}

	result['__tariff'] = $('.block_info .rate-plan_table td:first').text();
}

function LoadPreferences()
{
	preferences = AnyBalance.getPreferences();
	if(!preferences.login || preferences.login == '')
	{
		throw new AnyBalance.Error('Укажите логин');
	}
	if(!preferences.login.match(/^\d{10}$/))
	{
		throw new AnyBalance.Error('Неверный логин');
	}
	if(!preferences.password || preferences.password == '')
	{
		throw new AnyBalance.Error('Укажите пароль');
	}
	if(!preferences.date_format || preferences.date_format == '')
	{
		throw new AnyBalance.Error('Укажите формат даты');
	}
}

function Init()
{
	AnyBalance.setDefaultCharset('utf-8');
	dataElement = $('<data></data>');
	dataElement.appendTo('body');
	LoadPreferences();
	widgetUrl = widgetUrl.replace(/%LOGIN%/g, preferences.login).replace(/%PASSWORD%/g, encodeURIComponent(preferences.password));
}

function main()
{
	Init();
	try
	{
		ParseData(GetData());
		SetCounters();
	}
	finally
	{
		dataElement.remove();
	}
	result['success'] = true;
	AnyBalance.setResult(result);
}